import React, { useState, useEffect } from 'react';
import { ScrollView, View, Text, Dimensions, Alert, Modal, Pressable } from 'react-native';
import DeviceCard from '@/components/features/device/DeviceCard';
import SearchBar from '@/components/features/device/SearchBar';
import AddDeviceCard from '@/components/features/device/AddDeviceCard';
import { SceneCard } from '@/components/features/device/SceneCard';
import { getDevices, createDevice, getDeviceDetails, deleteDevice, updateDeviceState, getDeviceStateHistory } from '../../api/device';
// import { DeviceData } from '@/api/device';
import { getScenes, createScene, getSceneDetails, updateScene, deleteScene, addSceneDevice, 
    removeSceneDevice, adjustScenePriority, activateScene, getActiveScenes } from '../../api/scene';
import { get } from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
import { router, useFocusEffect } from 'expo-router';
import { getDisplayValueFromState } from '../../api/deviceStateMap';
import getDeviceImage from '../../api/getDeviceImage';
import { DEVICE_TYPES } from '../../constants/deviceParameters'; // 导入设备类型枚举

interface DeviceData {
    id: number;
    name: string;
    type: string;
    family: string;
    meta?: Record<string, any>;
    state: Record<string, any>;    
}

export default function DevicePage() {
    const [deviceList, setDeviceList] = useState<DeviceData[]>([]);
    const [isDeleteModalVisible, setDeleteModalVisible] = useState(false);
    const [deviceToDelete, setDeviceToDelete] = useState<DeviceData | null>(null);
    const deviceListWithAdd = [...deviceList, { id: 'add', isAdd: true }]
    // const [deviveListWithSearch, setDeviveListWithSearch] = useState<DeviceData[]>([]);
    const [searchQuery, setSearchQuery] = useState('');


    const handleTextChange = (text: string) => {
        setSearchQuery(text);
        // console.log('Search text:', text);
    };

    let filteredDeviceList = deviceList.filter(device =>
        device.name.toLowerCase().includes(searchQuery.toLowerCase())
    );

    let filteredDeviceListWithAdd = searchQuery
        ? [...filteredDeviceList]
        : [...filteredDeviceList, { id: 'add', isAdd: true }];
    
    useEffect(() => { 
        fetchDeviceList();
    }, []);

    useFocusEffect(
        React.useCallback(() => {
            fetchDeviceList();
        }, [])
    );

    const fetchDeviceList = async () => { 
        try {
            const response = await getDevices();
            const deviceList = response.data.data.devices;
            setDeviceList(deviceList);
            setDeviceList(Array.isArray(deviceList) ? deviceList : []);
        } catch (error) { 
            console.error('Get devices error:', error);
        }
    };

    return (
        <View style={{ flex: 1}}>
            <ScrollView style={{ flex: 1, backgroundColor: '#fff' }}>
                <Modal
                    animationType="fade"
                    transparent={true}
                    visible={isDeleteModalVisible}
                    onRequestClose={() => setDeleteModalVisible(false)}
                >
                    <View style={{
                        flex: 1,
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: 'rgba(0,0,0,0.5)',
                    }}>
                        <View style={{
                            width: 300,
                            padding: 20,
                            backgroundColor: 'white',
                            borderRadius: 10,
                            alignItems: 'center',
                        }}>
                            <Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 10 }}>
                                确认删除
                            </Text>
                            <Text>
                                确定要删除设备 "{deviceToDelete?.name}" 吗？
                            </Text>
                            <View style={{ flexDirection: 'row', marginTop: 20 }}>
                                <Pressable
                                    style={{
                                        padding: 10,
                                        marginRight: 10,
                                        backgroundColor: '#ccc',
                                        borderRadius: 5,
                                    }}
                                    onPress={() => setDeleteModalVisible(false)}
                                >
                                    <Text>取消</Text>
                                </Pressable>
                                <Pressable
                                    style={{
                                        padding: 10,
                                        backgroundColor: 'red',
                                        borderRadius: 5,
                                    }}
                                    onPress={async () => {
                                        if (deviceToDelete) {
                                            try {
                                                await deleteDevice(deviceToDelete.id.toString()); // 调用删除接口
                                                alert(`已被删除`);
                                                fetchDeviceList(); // 刷新列表
                                            } catch (error) {
                                                console.error('删除失败:', error);
                                                alert('无法删除设备，请重试');
                                            }
                                        }
                                        setDeleteModalVisible(false); // 关闭弹窗
                                    }}
                                >
                                    <Text style={{ color: 'white' }}>删除</Text>
                                </Pressable>
                            </View>
                        </View>
                    </View>
                </Modal>
                <View style={{ alignItems: 'center', marginTop: 44, marginBottom: 200 }}>
                    <View style={{ width: '100%', maxWidth: 400, alignItems: 'center' }}>
                        <SearchBar 
                            onChangeText={handleTextChange}
                        />
                        <Text
                            style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                alignSelf: 'flex-start',
                                marginLeft: 35,
                            }}
                        >
                            我的设备
                        </Text>
                    </View>
                    <View style={{ width: 330, marginTop: 20 }}>
                        {Array.from({ length: Math.ceil(filteredDeviceListWithAdd.length / 2) }).map((_, rowIdx) => (
                            <View
                                key={rowIdx}
                                style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-between',
                                    marginBottom: 12,
                                }}
                            >
                                {filteredDeviceListWithAdd.slice(rowIdx * 2, rowIdx * 2 + 2).map(device => (
                                    <View key={device.id} style={{ width: '48%', marginBottom: 8 }}>
                                        {'isAdd' in device && device.isAdd ? (
                                            <AddDeviceCard onDeviceSelect={() => {}} />
                                        ) : (
                                            <DeviceCard
                                                image={getDeviceImage((device as DeviceData).type)}
                                                title={'name' in device ? device.name : ''}
                                                desc={getDisplayValueFromState((device as DeviceData).state ?? {}) ?? '已停止'}
                                                onPress={() => router.push({
                                                    pathname: '/EditDeviceAC/[id]',
                                                    params: { id: device.id, deviceType: (device as DeviceData).type }
                                                })}
                                                onLongPress={() => {
                                                    setDeviceToDelete(device as DeviceData);
                                                    setDeleteModalVisible(true);
                                                }}
                                                // onPress={() => alert('暂未实现')}
                                            />
                                        )}
                                    </View>
                                ))}
                            </View>
                        ))}
                    </View>
                </View>
            </ScrollView>
        </View>
    );
}